import React, { useState, useEffect, useRef } from 'react';
import { SkinOutlined, CheckOutlined } from '@ant-design/icons';
import type { RadioChangeEvent } from 'antd';
import { Spin, Popover, Divider, Tooltip, Radio } from 'antd';
import styles from './index.less';
import { intl, intlItems } from '@/utils';
import { saveUserSetting } from '@/layouts/runtimeSettings';
import type { UserSettings } from '@/layouts/runtimeSettings';
import { useModel } from 'umi';

const ThemePopover: React.FC = () => {
  const { initialState, setInitialState } = useModel('@@initialState');
  const userSetting = useRef<UserSettings>({});
  const [currentTheme, setCurrentTheme] = useState('blue');
  /**
   * 实时切换
   */
  function setInitState() {
    setInitialState({
      ...initialState,
      settings: {
        ...initialState?.settings,
        ...userSetting.current,
      },
    });
  }

  // function onThemeChange(checked: boolean) {
  //   // userSetting.current = {
  //   //   ...userSetting.current,
  //   //   navTheme: checked ? 'dark' : 'light',
  //   // };
  //   // saveUserSetting(userSetting.current);
  //   // setInitState();
  //   setInitialState({
  //     ...initialState,
  //     settings: {
  //       ...initialState?.settings,
  //       navTheme: checked ? 'dark' : 'light',
  //     },
  //   });
  // }

  function siderWidthChange(e: RadioChangeEvent) {
    userSetting.current = {
      ...userSetting.current,
      siderWidth: e.target.value,
    };
    saveUserSetting(userSetting.current);
    setInitState();
  }

  const themeList = intlItems(
    'rc.themePop.color',
    [
      {
        key: 'red',
        title: '薄暮',
        color: '#D33237',
      },
      // {
      //   key: 'orange',
      //   title: '火山',
      //   color: '#e75f33',
      // },
      // {
      //   key: 'yellow',
      //   title: '日暮',
      //   color: '#efaf41',
      // },
      // {
      //   key: 'green',
      //   title: '极光绿',
      //   color: '#72c140',
      // },
      // {
      //   key: 'cyan',
      //   title: '明青',
      //   color: '#59bfc1',
      // },
      // {
      //   key: 'blue',
      //   title: '拂晓蓝',
      //   color: '#4290f7',
      // },
      {
        key: 'purple',
        title: '酱紫',
        color: '#6939c9',
      },
    ],
    'key',
  );

  const themeLightList = intlItems(
    'rc.themePop.isLight',
    [
      {
        key: 'light',
        title: '浅色',
        color: '#fff',
      },
      {
        key: 'dark',
        title: '深色',
        color: '#000',
      },
    ],
    'key',
  );

  function changeTheme(colorName: string, isLight: boolean) {
    // userSetting.current = {
    //   ...userSetting.current,
    //   primaryColor: theme.color
    // }
    // saveUserSetting(userSetting.current);
    // setInitState();
    let styleLink: HTMLLinkElement | null = document.getElementById(
      'theme-style',
    ) as HTMLLinkElement;
    let dxStyleLink: HTMLLinkElement | null = document.getElementById(
      'dx-theme-style',
    ) as HTMLLinkElement;

    if (styleLink !== null && dxStyleLink !== null) {
      // 假如存在id为theme-style 的link标签，直接修改其href
      if (isLight) {
        styleLink.href = `./theme/theme-${colorName}/ant.custom.light.css`;
        dxStyleLink.href = `./theme/theme-${colorName}/dx.generic.cpas-cloud-light-scheme.css`;
      } else {
        styleLink.href = `./theme/theme-${colorName}/ant.custom.dark.css`;
        dxStyleLink.href = `./theme/theme-${colorName}/dx.generic.cpas-cloud-dark-scheme.css`;
      }
    } else {
      // 不存在的话，则新建一个
      styleLink = document.createElement('link');
      styleLink.type = 'text/css';
      styleLink.rel = 'stylesheet';
      styleLink.id = 'theme-style';

      dxStyleLink = document.createElement('link');
      dxStyleLink.type = 'text/css';
      dxStyleLink.rel = 'stylesheet';
      dxStyleLink.id = 'dx-theme-style';
      if (isLight) {
        styleLink.href = `./theme/theme-${colorName}/ant.custom.light.css`;
        dxStyleLink.href = `./theme/theme-${colorName}/dx.generic.cpas-cloud-light-scheme.css`;
      } else {
        styleLink.href = `./theme/theme-${colorName}/ant.custom.dark.css`;
        dxStyleLink.href = `./theme/theme-${colorName}/dx.generic.cpas-cloud-dark-scheme.css`;
      }
      // styleLink.href = isLight
      //   ? (styleLink.href = `./theme/theme-${colorName}/ant.custom.light.css`)
      //   : (styleLink.href = `./theme/theme-${colorName}/ant.custom.dark.css`);
      document.body.append(styleLink);
      document.body.append(dxStyleLink);
      let bodyClassName = document.body.className;
      bodyClassName += ' dx-theme-generic-typography';
      document.body.className = bodyClassName;
    }

    setCurrentTheme(colorName);
    localStorage.setItem('themeData', colorName);
    localStorage.setItem('themeLight', isLight.toString());
  }

  useEffect(() => {
    const themeData = localStorage.getItem('themeData');
    const isLight = localStorage.getItem('themeLight') === 'true' ? true : false;
    if (themeData) {
      if (isLight !== undefined) {
        changeTheme(themeData, isLight);
      } else {
        changeTheme(themeData, true);
      }
    } else {
      changeTheme('red', true);
    }
  }, []);

  const loading = (
    <span className={`${styles.action} ${styles.account}`}>
      <Spin
        size="small"
        style={{
          marginLeft: 8,
          marginRight: 8,
        }}
      />
    </span>
  );

  if (!initialState) {
    return loading;
  }

  const { curUser } = initialState;

  if (!curUser || !curUser.username) {
    return loading;
  }

  const content = (
    <div style={{ width: 275, marginTop: 10, marginBottom: 10 }}>
      {/* <span>{intl('rc.themePop.theme', '深色模式')}：</span>
      <Switch
        checkedChildren="🌜"
        unCheckedChildren="🌞"
        defaultChecked={initialState.settings?.navTheme === 'dark'}
        onChange={onThemeChange}
      />
      <Divider /> */}
      <span> {intl('rc.themePop.siderWidth.title', '　侧边栏')}:</span>
      <Radio.Group
        options={[
          { label: intl('rc.themePop.siderWidth.def', '默认'), value: 208 },
          { label: '1x', value: 308 },
          { label: '2x', value: 408 },
        ]}
        style={{ marginLeft: 10 }}
        onChange={siderWidthChange}
        value={initialState.settings?.siderWidth || 208}
        optionType="button"
        buttonStyle="solid"
      />
      <Divider />
      <div style={{ display: 'flex', alignItems: 'center' }}>
        <span>{intl('rc.themePop.primaryColor', '　主题色')}：</span> <br />
        {themeList.map((theme) => (
          <Tooltip title={theme.title} key={theme.key}>
            <div
              key={theme.key}
              style={{
                width: 20,
                height: 20,
                marginRight: 8,
                backgroundColor: theme.color,
                cursor: 'pointer',
              }}
              onClick={() => {
                if (localStorage.getItem('themeLight')) {
                  changeTheme(
                    theme.key,
                    localStorage.getItem('themeLight') === 'true' ? true : false,
                  );
                } else {
                  changeTheme(theme.key, true);
                }
              }}
            >
              <CheckOutlined
                // style={{
                //   display: initialState.settings?.primaryColor === theme.color ? 'block' : 'none',
                //   color: 'white',
                //   marginTop: 3,
                // }}
                style={{
                  display: currentTheme === theme.key ? 'block' : 'none',
                  color: 'white',
                  marginTop: 3,
                }}
              />
            </div>
          </Tooltip>
        ))}
      </div>

      <Divider />
      <div style={{ display: 'flex', alignItems: 'center' }}>
        <span>{intl('rc.themePop.themeLight', '深浅色')}： </span> <br />
        {themeLightList.map((theme) => (
          <Tooltip title={theme.title} key={theme.key}>
            <div
              key={theme.key}
              style={{
                width: 20,
                height: 20,
                // marginLeft: 32,
                marginRight: 8,
                backgroundColor: theme.color,
                cursor: 'pointer',
                border: '1px solid grey',
              }}
              onClick={() => {
                if (localStorage.getItem('themeData')) {
                  changeTheme(
                    localStorage.getItem('themeData') as string,
                    theme.key === 'light' ? true : false,
                  );
                } else {
                  changeTheme('red', theme.key === 'light' ? true : false);
                }
              }}
            >
              <CheckOutlined
                // style={{
                //   display: initialState.settings?.primaryColor === theme.color ? 'block' : 'none',
                //   color: 'white',
                //   marginTop: 3,
                // }}
                style={{
                  display: currentTheme === theme.key ? 'block' : 'none',
                  color: 'white',
                  marginTop: 3,
                }}
              />
            </div>
          </Tooltip>
        ))}
      </div>
    </div>
  );

  return (
    <Popover content={content} title={intl('rc.themePop.title', '个性化设置')} trigger="click">
      <span className={`${styles.action} ${styles.account}`}>
        <SkinOutlined size={40} />
      </span>
    </Popover>
  );
};

export default ThemePopover;
